package com.englisheveryday.media;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;

import com.englisheveryday.R;
import com.englisheveryday.activity.MainActivity;
import com.englisheveryday.activity.PlayListActivity;
import com.englisheveryday.constants.Constants;
import com.englisheveryday.service.PlaylistService;
import com.englisheveryday.utils.L;
import com.englisheveryday.vo.PlaylistVO;

public class SimpleMediaPlayerService extends Service {

	private String file;
	private EEMediaPlayer mediaPlayer;
	private PlaylistService playlistService;
	private PlaylistVO currentAudio;
	private int currentPlayCount;//当前音频的播放次数
	private SharedPreferences.Editor editor;
	private SharedPreferences preferences;
	private IBinder serviceBinder = new ServiceBinder();
	private Intent playerInfoIntent = null;
	
	
	public void play(String id,int type){
		L.d("send");
		switch(type){
		case Constants.PLAYER_OPERATE_PLAY : {
			play(id);
		}
		break;
		case Constants.PLAYER_OPERATE_NEXT : {
			next();
		}
		break;
		case Constants.PLAYER_OPERATE_PRE : {
			pre();
		}
		break;
		case Constants.PLAYER_OPERATE_PAUSE : {
			L.d("onpause");
			pause();
		}
		break;
		case Constants.PLAYER_OPERATE_RESTART : {
			restart();
		}
		break;
		default : {
			
		}
		}
	}
	
	
	@Override
	public IBinder onBind(Intent intent) {
		L.d("bind");
		return serviceBinder;
	}
	
	/**
	 * 如果播放成功返回true
	 * @param file
	 * @return
	 */
	private boolean start(String file){
		L.d("file:"+file);
		try {
			if(mediaPlayer==null)
				return false;
			mediaPlayer.reset();
			mediaPlayer.setDataSource(Constants.BASEDIR+file);
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	
	/**
	 * 播放当前文件
	 * @param id
	 */
	private void play(String id){
		//查询待播放
		PlaylistVO vo = playlistService.findById(id);
		if(vo==null)
			return;
		currentAudio = vo;
		if(currentAudio!=null){
			start(currentAudio.getAudio());
		}
	}
	
	/**
	 * 播放下一个文件
	 * @param id
	 */
	private void next(){
		PlaylistVO vo  = playlistService.findNextById(getCurrentAudioId());
		if(vo==null)
			return;
		currentAudio = vo;
		if(currentAudio!=null){
			start(currentAudio.getAudio());
		}
	}
	
	/**
	 * 播放上一个文件
	 * @param id
	 */
	private void pre(){
		//查询待播放
		PlaylistVO vo = playlistService.findPreById(getCurrentAudioId());
		if(vo==null)
			return;
		currentAudio = vo;
		if(currentAudio!=null){
			start(currentAudio.getAudio());
		}
	}
	
	//停止
	private void stop(){
		if(mediaPlayer!=null&&mediaPlayer.isPlaying())
			mediaPlayer.stop();
	}
	
	
	//暂停
	public void pause(){
		L.d("pause");
		if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
			mediaPlayer.pause();
		}
	}
	
	/**
	 * 发送广播
	 * @param type
	 */
	private void sendBroadcasts(int type){
		playerInfoIntent.putExtra("id",currentAudio.getId());
		playerInfoIntent.putExtra("type",type);
		L.d("broadcast"+type);
		sendBroadcast(playerInfoIntent);
	}
	
	/**
	 * 保存播放位置
	 * @param duration
	 */
	private void saveCurrentPosition(int position){
		editor = preferences.edit();
		editor.putInt("time", position);
		editor.putString("id",currentAudio.getId());
		editor.commit();
	}
	
	/**
	 * 重置当前位置
	 */
	private void resetCurrentPosition(){
	    editor = preferences.edit();
		editor.putInt("time", 0);
		editor.putString("id",currentAudio.getId());
		editor.commit();
	}
	
	/**
	 * 获得当前播放位置
	 * @return
	 */
	private int getCurrentPosition(){
		return preferences.getInt("time",0);
	}
	
	/**
	 * 获得上次播放文件
	 * @return
	 */
	private String getCurrentAudioId(){
		return preferences.getString("id","");
	}
	
	/**
	 * 获得正在播放的音频
	 * @return
	 */
	private PlaylistVO getCurrentAudio(){
		if(currentAudio!=null)
			return currentAudio;
		return playlistService.findById(getCurrentAudioId());
	}
	
	//重新播放
	public void restart(){
		L.d("restart");
		try{
			//如果是已经播放
			if(mediaPlayer!=null){
				mediaPlayer.reset();
				mediaPlayer.setDataSource(Constants.BASEDIR+currentAudio.getAudio());
				mediaPlayer.prepare();
				mediaPlayer.seekTo(getCurrentPosition());
				mediaPlayer.start();
			}
		}catch(Exception  e){
			e.printStackTrace();
		}
		
	}
	
	//释放
	public void release(){
		if(mediaPlayer!=null){
			if(mediaPlayer.isPlaying())
				stop();
			mediaPlayer.release();
		}
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		L.d("oncreate");
		preferences = getSharedPreferences(Constants.SETTING_PLAYER, Context.MODE_PRIVATE);
		playlistService = new PlaylistService(this);
		mediaPlayer = new EEMediaPlayer();
		currentAudio = getCurrentAudio();
		playerInfoIntent = new Intent();
		playerInfoIntent.setAction("com.englisheveryday.mediaplayer.info");
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			@Override
			public void onCompletion(MediaPlayer mp) {
				playerInfoIntent.putExtra("id", currentAudio.getId());
				playerInfoIntent.putExtra("type",Constants.PLAYER_OPERATE_STOP);
				SimpleMediaPlayerService.this.sendBroadcast(playerInfoIntent);
				resetCurrentPosition();
				//判断播放模式
				int mode = preferences.getInt("mode", Constants.PLAYER_MODE_ORDER);
				switch(mode) {
				case Constants.PLAYER_MODE_ORDER : {
					next();
				}
				break;
				case Constants.PLAYER_MODE_SINGLER : {
					restart();
				}
				break;
				default : {
					
				}
				}
			}
		});
		mediaPlayer.setOnPauseListener(new EEMediaPlayer.OnStateChangeListener() {
			@Override
			public void onStateChanged() {
				sendBroadcasts(Constants.PLAYER_OPERATE_PAUSE);
				saveCurrentPosition(mediaPlayer.getCurrentPosition());
			}
		});
		mediaPlayer.setOnStartListener(new EEMediaPlayer.OnStateChangeListener() {
			@Override
			public void onStateChanged() {
				sendBroadcasts(Constants.PLAYER_OPERATE_PLAY);
				resetCurrentPosition();
				setNotification(currentAudio.getTitle());
			}
		});
		
		setNotification(currentAudio.getTitle());
		
	}

	public void setNotification(String title){
		Notification notification = new Notification(R.drawable.ic_launcher,title,
		        System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, MainActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(this, title,
		        "", pendingIntent);
		startForeground(1, notification);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		//释放播放器
		release();
		L.d("destroy");
		stopForeground(true);
	}

	public class ServiceBinder extends Binder {
		public SimpleMediaPlayerService getService(){
			return SimpleMediaPlayerService.this;
		}
	}

	
}
